package com.bsi.core.validate.handler;


import com.bsi.core.validate.rule.Validate;
import com.bsi.core.validate.rule.ValidateRule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.List;

/*
 * Author: liusongs
 * Date: 2019/10/26 10:19
 * Content:  执行校验操作,通过handler方法配合validateEnum中维护的validateRule规则类进行校验
 */

public class DefaultValidateHandler implements ValidateHandler {
    private static Logger LOGGER = LoggerFactory.getLogger(DefaultValidateHandler.class);

    /**
     * 校验传入的类，判断是否规则是否通过
     *
     * @param entity 传入需要进行校验的类
     * @return
     */
    @Override
    public boolean handler(Object entity) {
        Assert.notNull(entity, "ValidateHandler.handler --》 参数不能为空！");
//        if (!CollectionUtils.isEmpty(VALIDATEHANDLER_LIST)) {
//            for (ValidateRule rule : VALIDATEHANDLER_LIST
//            ) {
//                logger.info("====================[DefaultValidateHandler-》handler]开始调用:{}的check方法", rule.getClass().getSimpleName());
//                boolean check = rule.check(entity);
//                if (check == false) {
//                    return check;
//                }
//            }
//        }
        // 校验规则
        if (!CollectionUtils.isEmpty(VALIDATEHANDLER_LIST)) {
            // 获取传入类的所有属性
            List<Field> hasValidateFields = getHasValidateFields(entity.getClass());
            // 进行规则校验
            for (Field field : hasValidateFields) {
                Validate validate = field.getAnnotation(Validate.class);
                Class<? extends ValidateRule>[] value = validate.value();
                for (Class<? extends ValidateRule> aClass : value) {
                    String beanName = aClass.getSimpleName().substring(0, 1).toLowerCase() + aClass.getSimpleName().substring(1);
                    ValidateRule rule = VALIDATEHANDLER_LIST.get(beanName);
                    if (rule != null) {
                        boolean isPass = rule.checkField(entity, field);
                        if (!isPass) {
                            LOGGER.info("ValidateHandler.handler检测出{}类的{}属性为空--》", entity.getClass().getSimpleName(), field.getName());
                            return false;
                        }
                    }
                }
            }
        }
        return true;
    }

}
